<?php
class RM_User_AuthorizeNetController extends RM_Controller
{
    /**
     * Presnets the CC form
     */
    public function formAction()
    {
        for ($i = 1; $i <= 12; $i++) {
            $months[$i]['value'] = $i;
            if (strlen($i)==1){$text = "0".$i;}else{$text=$i;}
            $months[$i]['text'] = $text;
        }

        $count = 0;
        $yearnow = (int)date("Y");
        for ($i = $yearnow; $i <= $yearnow+10; $i++) {
            $expiry_years[$count]['value'] = $i;
            $expiry_years[$count]['text'] = $i;
            $count+=1;
        }
        $this->view->months = $months;
        $this->view->year_expire = $expiry_years;
    }

    /**
     * The ajax controller for processing the form details in real time.
     */
    public function processJsonAction(){
        $x_card_num = $this->_getParam('x_card_num');
        $cc_expire_date_month = $this->_getParam('cc_expire_date_month');
        $cc_expire_date_year = $this->_getParam('cc_expire_date_year');
        $x_card_code = $this->_getParam('x_card_code');

        // ZF 1.10 only
//        $valid = new Zend_Validate_CreditCard(array(
//            Zend_Validate_CreditCard::AMERICAN_EXPRESS,
//            Zend_Validate_CreditCard::VISA,
//            Zend_Validate_CreditCard::MASTERCARD,
//            Zend_Validate_CreditCard::DISCOVER
//        ));
        $valid = new Zend_Validate_CreditCard();
        if ($valid->isValid($x_card_num)) {
            
             // card valid

            $reservationDetails = RM_Reservation_Manager::getInstance()->getAllDetails();
            $reservationsModel = new RM_Reservations();
            $unitModel = new RM_Units;

            $lang = RM_Environment::getInstance()->getLocale();

            //$chargetotal = 0;

            $bookingref = RM_Reservation_Manager::getInstance()->getReservationID();

            // create the description text
            $description =  $bookingref.": ";
            $count = 1;
            foreach ($reservationDetails as $details){

                //$chargetotal = $chargetotal + $details->getTotal(); // get the total

                $unit = $details->getUnit();
                $period = $details->getPeriod();

                $unit_details = $unitModel->get($unit->getId(), $lang);
                $description .= $this->_translate->_( 'Admin.PayPal.Main', 'Selection')." ".$count."(".$unit_details->name." (".$unit->getId().") ".$period->getStart()." ".$this->_translate->_( 'Admin.PayPal.Main', 'to')." ".$period->getEnd().")";
                $count+=1;
            }

            $chargetotal = $reservationsModel->find($bookingref)->current()->getTotalPrice();

            $userdetails = RM_Reservation_Manager::getInstance()->getUser()->toArray();

            // gather the userdetails
            $userData['first_name'] = $userdetails['first_name'];
            $userData['last_name'] = $userdetails['last_name'];
            $userData['address'] = $userdetails['address1'];
            $userData['state'] = $userdetails['state'];
            $userData['zip'] = $userdetails['postcode'];
            $userData['country'] = $userdetails['country'];

            // gather the card details
            $ccArray['x_card_num'] = $x_card_num;
            $ccArray['x_exp_date'] = date("d",$cc_expire_date_month).date("y",$cc_expire_date_year);
            $ccArray['x_amount'] = $chargetotal;
            $ccArray['x_description'] = $description;
            $ccArray['x_card_code'] = $x_card_code;

            $AuthObj = new RM_Plugin_AuthorizeNet();
            $response = $AuthObj->Process($bookingref, $ccArray, $userData);

            if ((int)$response['ResponseReasonCode'] === 1) {
                // this is the return if the transaction passed
                $return = array(
                    "success" => true,
                    "authcode" => $response["AuthorizationCode"],
                    "transid" => $response["TransactionID"],
                    "bookingref" => $response["BookingRef"],
                    "amountcharged" => $response["Amount"],
                    "transtype" => $response["TransactionType"],
                    "msg" => $response["ResponseReasonText"],
                    "responsecode" => $response["ResponseReasonCode"]
                );

                // save the reservation
                RM_Log::toLog("Booking ref payment complete, by Authorize.net: ".$bookingref);

                $model = new RM_Reservations();
                $reservation = $model->find($bookingref)->current();
                RM_Log::toLog("Reservation Record ID: ".$reservation->id);

                $model->confirm($reservation);
                RM_Log::toLog("Confirmed Updated");

                $model->inProgressComplete($reservation);
                RM_Log::toLog("InProgress Marker Updated");

                $total_paid = $response["Amount"];

                RM_Log::toLog("Total Passed back from Authorize.net: ".$total_paid);

                $billingModel = new RM_Billing();
                $billingRow = $billingModel->createRow();
                $billingRow->reservation_id = $bookingref;
                $billingRow->total_paid = $total_paid;
                $billingID = $billingRow->save();

                RM_Log::toLog("Billing Updated");

                // save the payment information
                $billingPaymentsModel = new RM_BillingPayments();
                $billingPaymentRow = $billingPaymentsModel->createRow();
                $billingPaymentRow->id = $billingID;
                $billingPaymentRow->provider = "Authorize.Net";
                $billingPaymentRow->transaction_id = $response["TransactionID"];
                $billingPaymentRow->status = "success";
                $billingPaymentRow->total = $total_paid;
                $billingPaymentRow->transaction_date = Date("Y-m-d");
                $billingPaymentRow->save();

                RM_Log::toLog("Billing Payments Updated");


            } else {
                // this is the return if the transaction failed at Authorize.net
                $return = array(
                    "success" => false,
                    "authcode" => $response["AuthorizationCode"],
                    "transid" => $response["TransactionID"],
                    "bookingref" => $response["BookingRef"],
                    "amountcharged" => $response["Amount"],
                    "transtype" => $response["TransactionType"],
                    "msg" => $response["ResponseReasonText"],
                    "responsecode" => $response["ResponseReasonCode"]
                );
            }


        } else {
            // this is the return if the card number is not valid
            $return = array(
                "success" => false,
                "authcode" => 0,
                "transid" => 0,
                "bookingref" => 0,
                "amountcharged" => 0,
                "transtype" => 0,
                "msg" => $this->_translate->_('User.AuthorizeNet.Main','CardNumberNotValid'),
                "responsecode" => 0
            );
        }
        return array(
            'data' => $return
        );
       
    }

    public function ccFormAction(){

    }
    
    public function cancelAction(){
        //We need to reset user object accorting to ticket #59 in Trac
        RM_Reservation_Manager::getInstance()->resetUser();

        // return a cancelled message
        return array(
            'data' => array('success' => true)
        );
    }

    public function successAction(){

        RM_Reservation_Manager::getInstance()->setPaymentStatus(RM_Payments_Status::TRANSACTION_END_SUCCESSFULLY);
        $this->_forward('success', 'payments');
    }
}